import { createPinia } from 'pinia'
import { defineStore } from 'pinia'

const pinia = createPinia()

export default pinia

// 用户信息store
export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    token: null,
    refreshToken: null,
    justLoggedIn: false // 新增：标识刚登录状态
  }),
  getters: {
    isLoggedIn: (state) => !!state.token,
    isAuthenticated: (state) => !!state.token,
    isAdmin: (state) => {
      if (!state.userInfo) return false
      // 检查用户类型是否为管理员
      return state.userInfo.userType === 'ADMIN' || state.userInfo.userType === 'admin'
    },
    hasPermission: (state) => (permission) => {
      if (!state.userInfo) return false
      // 管理员拥有所有权限
      if (state.userInfo.userType === 'ADMIN' || state.userInfo.userType === 'admin') {
        return true
      }
      // 普通用户检查具体权限
      return state.userInfo.permissions && state.userInfo.permissions.includes(permission)
    }
  },
  actions: {
    setUserInfo(info) {
      this.userInfo = info
    },
    setToken(token) {
      this.token = token
    },
    setRefreshToken(refreshToken) {
      this.refreshToken = refreshToken
    },
    // 保存登录结果
    saveLoginResult(result) {
      this.token = result.token
      this.refreshToken = result.refreshToken
      
      // 确保用户信息中包含id字段
      if (result.userInfo) {
        // 如果后端返回的是userId而不是id，进行转换
        if (!result.userInfo.id && result.userInfo.userId) {
          result.userInfo.id = result.userInfo.userId
        }
        this.userInfo = result.userInfo
      } else {
        this.userInfo = {}
      }
      
      // 只在store中统一处理localStorage存储，避免重复存储
      localStorage.setItem('token', result.token)
      localStorage.setItem('refreshToken', result.refreshToken)
      localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
    },
    logout() {
      this.userInfo = null
      this.token = null
      this.refreshToken = null
      this.justLoggedIn = false
      localStorage.removeItem('token')
      localStorage.removeItem('refreshToken')
      localStorage.removeItem('userInfo')
    },

    // 管理员登录
    async adminLogin(credentials) {
      try {
        const response = await fetch('http://localhost:8080/api/auth/login', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(credentials)
        })

        if (!response.ok) {
          const error = await response.json()
          throw new Error(error.message || '登录失败')
        }

        const data = await response.json()
        console.log('登录返回数据:', data) // 调试日志
        
        // 检查是否为管理员 - 修复逻辑：使用userType字段直接判断
        const userType = data.userType || (data.userInfo && data.userInfo.userType)
        console.log('用户类型:', userType) // 调试日志
        
        if (userType === 'ADMIN' || userType === 'admin') {
          this.token = data.token
          this.refreshToken = data.refreshToken
          this.userInfo = data.userInfo || data // 兼容不同的数据格式
          this.justLoggedIn = true // 设置刚登录标志
          localStorage.setItem('token', data.token)
          localStorage.setItem('refreshToken', data.refreshToken)
          localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
          return data
        } else {
          throw new Error('您没有管理员权限')
        }
      } catch (error) {
        throw error
      }
    },
    loadUserInfo() {
      const token = localStorage.getItem('token')
      const refreshToken = localStorage.getItem('refreshToken')
      const userInfoStr = localStorage.getItem('userInfo')
      
      if (token && userInfoStr) {
        try {
          const userInfo = JSON.parse(userInfoStr)
          // 确保用户信息中包含id字段
          if (!userInfo.id && userInfo.userId) {
            userInfo.id = userInfo.userId
          }
          this.token = token
          this.refreshToken = refreshToken
          this.userInfo = userInfo
        } catch (error) {
          console.error('解析用户信息失败:', error)
          this.logout()
        }
      }
    },
    // 刷新token后的更新
    updateAfterRefresh(result) {
      this.token = result.token
      this.refreshToken = result.refreshToken
      this.userInfo = result.userInfo
      localStorage.setItem('token', result.token)
      localStorage.setItem('refreshToken', result.refreshToken)
      localStorage.setItem('userInfo', JSON.stringify(result.userInfo))
    },
    // 更新用户信息
    updateUserInfo(userInfo) {
      if (this.userInfo) {
        // 合并新旧用户信息
        this.userInfo = { ...this.userInfo, ...userInfo }
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
      }
    }
  }
})

// 购物车store
export const useCartStore = defineStore('cart', {
  state: () => ({
    items: []
  }),
  getters: {
    totalItems: (state) => state.items.reduce((total, item) => total + item.quantity, 0),
    totalPrice: (state) => state.items.reduce((total, item) => total + (item.price * item.quantity), 0)
  },
  actions: {
    addToCart(product, quantity = 1) {
      const existingItem = this.items.find(item => item.id === product.id)
      if (existingItem) {
        existingItem.quantity += quantity
      } else {
        this.items.push({
          ...product,
          quantity
        })
      }
      this.saveCart()
    },
    removeFromCart(productId) {
      this.items = this.items.filter(item => item.id !== productId)
      this.saveCart()
    },
    updateQuantity(productId, quantity) {
      const item = this.items.find(item => item.id === productId)
      if (item) {
        item.quantity = quantity
        if (item.quantity <= 0) {
          this.removeFromCart(productId)
        } else {
          this.saveCart()
        }
      }
    },
    clearCart() {
      this.items = []
      this.saveCart()
    },
    saveCart() {
      localStorage.setItem('cart', JSON.stringify(this.items))
    },
    loadCart() {
      const cart = localStorage.getItem('cart')
      if (cart) {
        this.items = JSON.parse(cart)
      }
    }
  }
})

// 产品store
export const useProductStore = defineStore('product', {
  state: () => ({
    products: [],
    categories: [],
    loading: false,
    error: null
  }),
  getters: {
    getProductById: (state) => (id) => {
      return state.products.find(product => product.id === id)
    }
  },
  actions: {
    setProducts(products) {
      this.products = products
    },
    setCategories(categories) {
      this.categories = categories
    },
    setLoading(loading) {
      this.loading = loading
    },
    setError(error) {
      this.error = error
    }
  }
})